/**
 * @author Kevin.MOU
 * Login view script Support
 */
(function($) {
	var Login = {
		singleProject : true,
		onRemember : function(e) {
			e.preventDefault();
			$("#remember").toggleClass('checkbox_checked');
		},

		onSubmit : function(username, password, remoteKey, verify) {
			var a = this;
			busy(1, $F.lang('submit'));
			let loginRequest = {
				useLang: a.language,
				epid : '',
				loginId : username,
				password : $F.encPwd(password, a),
				uid: a.uid
			};
			if (Login.thirdlVGroovyUrl)
				loginRequest.thirdPassword = password;
			let dataRequest = $.extend(a.requestQueries, {
				uid: a.uid,
				captcha: (verify ? verify.toUpperCase() : ''),
				language: a.language,
				payload: JSON.stringify(loginRequest)
			});
			Ajax.post({
				url : a.url + '/portal/login_?ds=' + a.dataService.key,
				data : dataRequest,
				success : function(data) {
					// console.log(data);
					if (data.code > 0) {
						if ($("#remember").hasClass("checkbox_checked")) {
							$.cookie("clogin_username", username, {
								expires : 30
							});
							console.log("Save cookies: clogin_username");
						} else {
							$.cookie("clogin_username", null);
							console.log("Remove cookies: clogin_username");
						}
						$('#vid').hide();
						location.href = Login.url + '/portal';
					} else {
						$('img.verifyCode').click();
						$('input#verify').val('');
						Login.verifyLock = true;
						$('div.login_help_panel').before(Login.verifier.show());

						switch(data.code) {
						case -101:	// 密码为空
						case -102:	// 密码过期
						case -103:	// 密码过期（无修改时间）
							showError(data.message);
							a.pwdChange(username, '', data);
							break;
						default:
							showError(data.message);
						}
						busy(0);
					}
				},
				fail : function(jqXHR, textStatus, errorThrown) {
					showError('[' + jqXHR.status + '] ' + jqXHR.statusText);
					busy(0);
				}
			});
		},

		onSubmitSAAS : function(epid, username, password, remoteKey, verify) {
			var a = this;
			if (epid == '')
				epid = 'MainDB';
			else
				epid = epid.toUpperCase();

			busy(1, $F.lang('submit'));
			var dataRequest = $.extend(a.requestQueries, {
				uid: a.uid,
				captcha: (verify ? verify.toUpperCase() : ''),
				language: a.language,
				payload: JSON.stringify({
					useLang: a.language,
					epid : epid,
					loginId : username,
					password : $F.encPwd(password, a),
					uid: a.uid
				})
			});
			Ajax.post({
				url : a.url + '/portal/login_?ds=' + a.dataService.key,
				data : dataRequest,
				success : function(data) {
					// console.log(data);
					if (data.code > 0) {
						if ($("#remember").hasClass("checkbox_checked")) {
							$.cookie("clogin_username", username, {
								expires : 30
							});
							$.cookie("clogin_epid", epid, {
								expires : 30
							});
							console.log("Save cookies: clogin_epid, clogin_username");
						} else {
							$.cookie("clogin_username", null);
							$.cookie("clogin_epid", null);
							console.log("Remove cookies: clogin_epid, clogin_username");
						}
						$('#vid').hide();
						location.href = Login.url + '/portal';
					} else {
						$('img.verifyCode').click();
						Login.verifyLock = true;
						$('div.login_help_panel').before(Login.verifier.show());

						switch(data.code) {
						case -101:	// 密码为空
						case -102:	// 密码过期
						case -103:	// 密码过期（无修改时间）
							showError(data.message);
							a.pwdChange(username, epid, data);
							break;
						default:
							showError(data.message);
						}
						busy(0);
					}
				},
				fail : function(jqXHR, textStatus, errorThrown) {
					showError(textStatus);
					busy(0);
				}
			});
		},

		pwdChange : function(username, epid, data) {
			$('.login_panel').hide();
			var a = this,
				panel = $('.pwdchange').show(),
				err = $('.pc_err', panel).text(data.message).show(),
				dbpool = Login.dataService.dbPool;

			$('.js_cancel', panel).off('click').on('click', function(){
				panel.hide();
				$('.login_panel').show();
			})
			$('.js_submit', panel).off('click').on('click', function(){
				var oldpwd = $('input[name=oldpwd]', panel).focus(),
					newpwd = $('input[name=newpwd]', panel),
					newpwd2 = $('input[name=newpwd2]', panel);

				if (! newpwd.val()) {
					err.text('新密码不可为空').show();
					newpwd.focus();
					return;
				}
				if (newpwd2.val() !== newpwd.val()) {
					err.text('重复密码不相同').show();
					newpwd2.focus();
					return;
				}

				var sqldata = {
					name: "System.StaffInfo.ChangeN",
					epId: epid,
					dbPool: dbpool || '',
					loginId: username,
					o: $F.encPwd(oldpwd.val(), a),
					n: $F.encPwd(newpwd.val(), a, true),
					uid: a.uid,
					custF: 1
				}
				// console.info('Change password', sqldata)
				Ajax.post({
					url : getServiceMethod('JSGenerateServlet2_1'),
					data : JSON.stringify(sqldata),
					headers : {
						THREADID: Date.now(),
						DS: a.dataService.key
					},
					contentType : 'json',
					success : function(data) {
						if (data.code > 0) {
							panel.hide();
							$('.login_panel').show();
							showError($F.lang('pwdModifiedAndRelogin'))
						} else {
							// console.log(data)
							switch(data.code) {
							case -7:
								err.text($F.lang('wrongOriginalPwdError')).show();
								break;
							case -100:
								var message = '';
								switch(data.value) {
								case -1:
									message = $F.lang('pwdLength');
									break;
								case -2:
									message = $F.lang('pwdCap');
									break;
								case -3:
									message = $F.lang('pwdDigit');
									break;
								case -4:
									message = $F.lang('pwdSC');
									break;
								case -5:
									message = $F.lang('pwdContinues');
									break;
								case -6:
									message = $F.lang('pwdKC');
									break;
								}
								err.text(message).show();
								break;
							default:
								err.text(data.message).show();
								break;
							}
						}
					}
				})

			})
		}
	};

	var init = function() {
		Login.rsaPubKey = $('input#rsaPubKey').val();
		Login.requestQueries = $.extend(true, {}, Request.queryStrings());
		$('.login_box').draggable({
			handle: '.login_side'
		})
		$(".login_side").fadeIn(1000);

		var cs = [];
		for(var key in Login.languages) {
			cs.push({
				value: key,
				label: Login.languages[key]
			})
		}
		$('.login_language').wisCombox({
			tip : $F.lang('language'),
			onSelected : function(data) {
				$.cookie("language", data.value, {
					expires : 30
				});
				location.reload(true);
			}
		}).setData(cs).val(Login.language);

		if (Login.dataService.saas) {
			// SAAS模式登录
			$('.login_epid').show();
			// 设置输入中的回车
			$("input#epid").keydown(function(e) {
				if (e.keyCode == 13) {
					e.preventDefault();
					$("input#username").select().focus();
				}
			});
			$("input#username").keydown(function(e) {
				if (e.keyCode == 13) {
					e.preventDefault();
					$("input#password").select().focus();
				}
			});

			// 取cookie值
			var username = $.cookie("clogin_username"), epid = $.cookie("clogin_epid");
			if (username != null) {
				$("#remember").addClass("checkbox_checked");
				$("input#epid").val(epid);
				$("input#username").val(username).trigger('change');
			} else {
				$("#remember").removeClass("checkbox_checked");
			}
			$("input#epid").focus();
		} else {
			// 普通模式登录
			$('.login_epid').hide();
			var unInput = $('input#username').on('change', function(e) {
				var username = $(e.target).val();
				if (username == Login.username)
					return;
				Login.username = username;
			});

			if($('input#username').prop('disabled')){
				var username = $('input#username').val();
				if (username == Login.username)
					return;
				Login.username = username;
			}
			// 取cookie值
			var username = $.cookie("clogin_username");
			if (username !== null) {
				$("#remember").addClass("checkbox_checked");
				$("input#username").val(username).trigger('change');
			} else {
				$("#remember").removeClass("checkbox_checked");
				$("input#username").val('');
				$("input#password").val('');
			}
			$("input#username").focus();
		}

		var form = $('form.login_form');
		$('button.verifyCode', form).on('click', function(e) {
			var epid = $("input#epid", form).val(), username = $("input#username", form).val();
			if (! username)
				return showError('请输入用户登录名');

			$(".login_err_panel").hide();
			$F.await(function(go){
				Ajax.post({
					url: Login.url + '/loginVerify_?t=' + Date.now(),
					data: {
						c: 'sms',
						uid: Login.uid,
						ecsid: 'ngs',
						epid: epid,
						username: username,
						dbpool: '',
						ds: Login.dataService.key
					},
					success : function(data) {
						if (data.code > 0) {
							$F.info(data.message);
							makeVerifyState($(e.currentTarget))
						} else
							showError(data.message);
					},
					always: function(data) {
						go();
					}
				})
			});
		})
		$('img.verifyCode', form).on('click', function(e) {
			//console.log('Change verify code')
			var src = $(this).attr('src');
			src = src.substring(0, src.lastIndexOf('&'))
			$(this).attr('src', src + '&t=' + Date.now())
		})
		Login.verifier = $('div.login_verify', form);
		if (Login.verifyLock) Login.verifier.show();
		else Login.verifier.remove();

		form.on('submit', function(e) {
			e.preventDefault();
			var form = $("form.login_form"),
				epid = $("input#epid", form).val(),
				username = $("input#username", form).val(),
				password = $("input#password", form).val();

			// console.log(password);
			let remoteKey = localStorage.getItem("elite_remote_key");
			if (!remoteKey) {
				remoteKey = Guid.raw();
				localStorage.setItem("elite_remote_key", remoteKey);
			}

			$(".login_err_panel").hide();
			if (Login.verifyLock && $('body').hasClass('slider')) {
				SlideUnlocker.init({
					lang: Login.language,
					onLoad: function(callback) {
						Ajax.post({
							url: Login.url + '/slidelock.load_',
							data: {
								uid: Login.uid,
								ecsid: 'portal'
							},
							dataType: 'binary',
							success: function(data) {
								callback(data);
							}
						})
					},
					onVerify : function(pos, callback) {
						Ajax.post({
							url: Login.url + '/slidelock.verify_',
							data: {
								uid: Login.uid,
								ecsid: 'portal',
								pos: pos
							},
							success: function(data) {
								callback(data, function() {
									if (Login.dataService.saas)
										Login.onSubmitSAAS(epid, username, password, remoteKey, $('input#verify').val());
									else
										Login.onSubmit(username, password, remoteKey, $('input#verify').val());
								});
							}
						});
					}
				});
			} else {
                if (Login.dataService.saas)
                    Login.onSubmitSAAS(epid, username, password, remoteKey, $('input#verify').val());
                else
                    Login.onSubmit(username, password, remoteKey, $('input#verify').val());
			}
		})
	},

	makeVerifyState = function(t) {
		t.attr('disabled', true);
		t.forceClass('disabled');
		var wait = function(v) {
			t.text(v + Language.verifyProcess);
			v --;
			if (v > 0)
				setTimeout(function(){
					wait(v)
				}, 1000)
			else
				t.removeClass('disabled').attr('disabled', false).text(Language.verify);
		}
		wait(60);
	},

	getServiceMethod = function(method) {
		var serviceUrl = Login.dataService.url;
		if (serviceUrl.toLowerCase().startWith('http')) {
			return Login.url + '/proxy?method=' + method;
		} else {
			// 直接访问同一个JVM下的其他WebApp服务
			return method? (serviceUrl + '/' + method) : serviceUrl;
		}
    },

	busy = function(e, m) {
		if (e == 1) {
			$(".login_btn").hide();
			$(".login_busy").show().find('>span').text(m);
		} else {
			$(".login_busy").hide();
			$(".login_btn").show();
		}
	},

	showError = function(e) {
		$("#err_tips").text(e);
		$(".login_err_panel").show();
	},

	resizeBackground = function() {
		var bg = $('#bgDiv'), vid = $('#vid'), docHeight = $('body').innerHeight(), docWidth = $('body').innerWidth();
		if (docWidth / docHeight > 1920 / 1080) {
			var vh = (docWidth * 1080) / 1920;
			if (vh > docHeight) {
				bg.css({
					left: 0,
					top: (docHeight - vh) /2 + 'px'
				})
			} else {
				bg.css({
					left: 0,
					top: 0
				})
			}
			bg.css({
				width: docWidth,
				height: vh
			})
		} else {
			var vw = (docHeight * 1920) / 1080;
			if (vw > docWidth) {
				bg.css({
					left: (docWidth - vh) /2 + 'px',
					top: 0
				})
			} else {
				bg.css({
					left: 0,
					top: 0
				})
			}
			bg.css({
				width: vw,
				height: docHeight
			})
		}
	}

	window.Login = Login;

	$(function() {
		var bg = $('#bgDiv'), vid = $('#vid'), img = new Image();
		$(window).on('resize', function(e){
			resizeBackground()
		}).trigger('resize');

		img.src = Login.url + '/images/background.jpg';
		img.onload = function() {
			bg.css({
				opacity: 1,
				backgroundImage : 'url(' + img.src + ')'
			})
		}
		vid.bind('canplay', function() {
			vid.css({opacity: 0.5})
		})

		init();
	});
})(jQuery);
